<!-- 客户 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="lawFirmName">
              <el-input
                v-model="queryParams.lawFirmName"
                placeholder="律所名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button type="success" @click="handleOpenDialog()">
                  <i-ep-plus />
                  新增
                </el-button>
                <!-- <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                >
                  <i-ep-delete />
                  批量删除
                </el-button> -->
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              align="center"
              prop="id"
              width="80"
            />

            <el-table-column
              key="lawFirmName"
              label="律所名称"
              align="center"
              prop="lawFirmName"
              width="180"
            />

            <el-table-column label="地点" align="center" prop="address" />

            <el-table-column
              label="所属城市"
              width="180"
              align="center"
              prop="belongCityName"
            />

            <el-table-column
              label="手机号/座机号"
              align="center"
              prop="phone"
              width="120"
            />

            <el-table-column label="创建时间" align="center">
              <template #default="scope">
                <text>
                  {{
                    new Date(scope.row.createdAt)
                      .toISOString()
                      .replace("T", " ")
                      .substring(0, 19)
                  }}
                </text>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row.id)"
                >
                  <i-ep-edit />
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      @close="handleCloseDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="律所名称" prop="lawFirmName">
          <el-input
            v-model="formData.lawFirmName"
            placeholder="请输入律所名称"
          />
        </el-form-item>

        <el-form-item label="律所地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入律所地址" />
        </el-form-item>

        <el-form-item label="所属城市" prop="belongCityNo">
          <el-cascader
            v-model="formData.belongCityNo"
            :options="cityData"
            style="width: 100%"
            :props="cascaderProps"
            :show-all-levels="false"
            @change="cityCascaderChange"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Customers",
  inheritAttrs: false,
});

import lawfirmAPI, {
  LawFirmQuery,
  LawFirmForm,
  LawFirmVO,
} from "@/api/lawfirm";
import cityAPI from "@/api/city";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<LawFirmVO[]>();
/** 城市列表 */
const cityData = ref<any>([]);
const cascaderProps = {
  label: "name",
  value: "id",
  children: "children",
  emitPath: false,
};
/** 用户查询参数  */
const queryParams = reactive<LawFirmQuery>({
  cityNo: "",
  lawFirmName: "",
  current: 1,
  pageSize: 10,
});

/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 用户表单数据
const formData = reactive<LawFirmForm>({
  id: undefined,
  address: "",
  belongCityName: "",
  belongCityNo: undefined,
  createdAt: "",
  lawFirmName: "",
  lawFirmNo: undefined,
  phone: "",
  updateAt: "",
});

/** 用户表单校验规则  */
const rules = reactive({
  lawFirmAdmin: [
    { required: true, message: "是否律所管理员不能为空", trigger: "blur" },
  ],
  lawyerName: [{ required: true, message: "律所不能为空", trigger: "blur" }],
  careerTime: [
    { required: true, message: "执业年长不能为空", trigger: "blur" },
  ],
  belongCityName: [
    { required: true, message: "地址不能为空", trigger: "blur" },
  ],
  categoryLabel: [{ required: true, message: "领域不能为空", trigger: "blur" }],
  lawFirmName: [{ required: true, message: "律所不能为空", trigger: "blur" }],
  phone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  lawfirmAPI
    .getLawfirm(queryParams)
    .then((data) => {
      // console.log(data, "查询律所列表");
      pageData.value = data.records;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  cityData.value = await cityAPI.getCity();
  if (id) {
    dialog.title = "修改用户";
    lawfirmAPI.getLawfirmById(id).then((data) => {
      Object.assign(formData, {
        ...data,
        belongCityNo: Number(data.belongCityNo),
      });
    });
  } else {
    dialog.title = "新增用户";
  }
}
/** 城市选择时触发 */
const cityCascaderChange = (item: any) => {
  // console.log(item, formData, "城市选择");
  let address = findById(cityData.value, item);
  formData.belongCityName = address.name;
};
/** 遍历找到对应的城市数据 */
function findById(arr: any, id: number) {
  // console.log(arr, id, "arr");
  // 遍历数组中的每个元素
  for (let i = 0; i < arr.length; i++) {
    // 检查当前元素的id是否匹配
    if (arr[i].id === id) {
      // 如果匹配，返回当前元素
      return arr[i];
    }
    // 如果当前元素有children数组，递归查找
    if (arr[i].children && arr[i].children.length > 0) {
      const result: any = findById(arr[i].children, id);
      if (result) {
        // 如果在children中找到了匹配项，返回它
        return result;
      }
    }
  }
  // 如果没有找到匹配项，返回null或undefined（这里返回null表示明确没有找到）
  return null;
}
/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      lawfirmAPI
        .updateLawfirm(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("修改用户成功");
          } else {
            ElMessage.success("新增用户成功");
          }
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      lawfirmAPI
        .deleteLawfirm(Number(userIds))
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
